package cn.ze.yygh.cmn.service.impl;

import cn.ze.yygh.cmn.listener.DictListener;
import cn.ze.yygh.cmn.mapper.DictMapper;
import cn.ze.yygh.cmn.service.DictService;

import cn.ze.yygh.model.cmn.Dict;
import cn.ze.yygh.model.hosp.HospitalSet;
import cn.ze.yygh.vo.cmn.DictEeVo;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.annotations.Api;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    //mp 框架已经帮忙自动注入了mapper  使用basemapper即可


    //根据ID 查询 子数据
    @Override
    //将数据缓存在redis   ===>   <key,dict>  key 由keyGenerator 定义的方式生成
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    public List<Dict> findChildData(Long id) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("parent_id",id);
        List<Dict> list = baseMapper.selectList(wrapper);
        //向list集合的每个对象中设置hasChildren的值
        for (Dict dict : list) {
            Long dictId = dict.getId();
            dict.setHasChildren(this.hasChildren(dictId));
        }
        return list;
    }



    //判断id下面是否有子数据
    private boolean hasChildren(Long id){
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("parent_id",id);
        Integer count = baseMapper.selectCount(wrapper);
        return count > 0;
    }

    //导出数据字典
    @Override
    public void exportDictData(HttpServletResponse response) {
        //设置下载信息
        //设置响应类型
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = "dict";
        //设置头信息  让操作以下载方式打开
        response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
        //查询数据库
        List<Dict> dictList = baseMapper.selectList(null);
        //Dict ---> DictEnVo
        List<DictEeVo> dictVoList = new ArrayList<>();
        for (Dict dict : dictList) {
            DictEeVo dictEeVo = new DictEeVo();
            BeanUtils.copyProperties(dict,dictEeVo);
            dictVoList.add(dictEeVo);

        }
        //调用方法进行写操作
        try {
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("dict")
                    .doWrite(dictVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //导入数据字典
    @Override
    //清空缓存设置
    @CacheEvict(value = "dict",allEntries = true)
    public void importDictData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getDictName(String dictCode, String value) {
        //判断dictCode 是否为空
        if(StringUtils.isEmpty(dictCode)){
            //直接根据value查询
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("value",value);
            Dict dict = baseMapper.selectOne(wrapper);
            return dict.getName();
        }else{
            //直接根据value和dictCode查询
            //先根据dictCode 查到 ID
            Dict codeDict = this.getDictByDictCode(dictCode);
            //再根据ID查到的对象的parentID查
            Long parent_id = codeDict.getId();
            //根据parent_id   value 查询
            Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>()
                    .eq("parent_id", parent_id)
                    .eq("value", value));
            return dict.getName();
        }
    }

    //根据dictCode 获取下级结点
    @Override
    public List<Dict> findByDictCode(String dictCode) {
       //先根据dictCode 获取对应id
        Dict dict = this.getDictByDictCode(dictCode);
        // 根据ID获取子结点
        List<Dict> list = this.findChildData(dict.getId());
        return list;
    }

    private Dict getDictByDictCode(String dictCode){
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code",dictCode);
        Dict codeDict = baseMapper.selectOne(wrapper);
        return codeDict;
    }
}
